import axios from 'axios';

// GitHub OAuth配置
export const GITHUB_CONFIG = {
  // GitHub Client ID，从环境变量获取
  clientId: process.env.GITHUB_CLIENT_ID || '',
  // GitHub Client Secret，从环境变量获取
  clientSecret: process.env.GITHUB_CLIENT_SECRET || '',
  // GitHub OAuth URLs
  tokenUrl: 'https://github.com/login/oauth/access_token',
  userUrl: 'https://api.github.com/user',
};

/**
 * 使用授权码获取GitHub访问令牌
 * @param code GitHub授权码
 * @returns GitHub访问令牌
 */
export const getGitHubAccessToken = async (code: string): Promise<string> => {
  try {
    const response = await axios.post(
      GITHUB_CONFIG.tokenUrl,
      {
        client_id: GITHUB_CONFIG.clientId,
        client_secret: GITHUB_CONFIG.clientSecret,
        code: code,
      },
      {
        headers: {
          Accept: 'application/json',
        },
      }
    );

    if (response.data.error) {
      // 处理特定的GitHub OAuth错误
      const errorType = response.data.error;
      const errorDescription = response.data.error_description;
      
      if (errorType === 'bad_verification_code') {
        throw new Error('授权码已过期或无效，请重新登录');
      }
      if (errorType === 'incorrect_client_credentials') {
        throw new Error('GitHub应用配置错误，请联系管理员');
      }
      if (errorType === 'redirect_uri_mismatch') {
        throw new Error('回调地址不匹配，请联系管理员');
      }
      
      throw new Error(errorDescription || 'GitHub授权失败');
    }

    if (!response.data.access_token) {
      throw new Error('未收到有效的访问令牌');
    }

    return response.data.access_token;
  } catch (error) {
    console.error('获取GitHub访问令牌失败:', error);
    if (error instanceof Error) {
      // 如果是我们自定义的错误，直接抛出
      if (error.message.includes('授权码已过期') || 
          error.message.includes('应用配置错误') ||
          error.message.includes('回调地址不匹配')) {
        throw error;
      }
      throw new Error(`GitHub授权失败: ${error.message}`);
    }
    throw new Error('GitHub授权失败');
  }
};

/**
 * 使用访问令牌获取GitHub用户信息
 * @param accessToken GitHub访问令牌
 * @returns GitHub用户信息
 */
export const getGitHubUserInfo = async (accessToken: string) => {
  try {
    const response = await axios.get(GITHUB_CONFIG.userUrl, {
      headers: {
        Authorization: `token ${accessToken}`,
        Accept: 'application/json',
      },
    });

    const userData = response.data;

    return {
      githubId: userData.id.toString(),
      username: userData.login,
      email: userData.email,
      name: userData.name,
      picture: userData.avatar_url,
      bio: userData.bio,
      location: userData.location,
      publicRepos: userData.public_repos,
      followers: userData.followers,
      following: userData.following,
    };
  } catch (error) {
    console.error('获取GitHub用户信息失败:', error);
    if (error instanceof Error) {
      throw new Error(`获取GitHub用户信息失败: ${error.message}`);
    }
    throw new Error('获取GitHub用户信息失败');
  }
};

/**
 * 验证GitHub授权码并获取用户信息
 * @param code GitHub授权码
 * @returns GitHub用户信息
 */
export const verifyGitHubCode = async (code: string) => {
  try {
    // 1. 使用授权码获取访问令牌
    const accessToken = await getGitHubAccessToken(code);
    
    // 2. 使用访问令牌获取用户信息
    const userInfo = await getGitHubUserInfo(accessToken);
    
    return userInfo;
  } catch (error) {
    console.error('GitHub授权验证失败:', error);
    if (error instanceof Error) {
      throw new Error(`GitHub授权验证失败: ${error.message}`);
    }
    throw new Error('GitHub授权验证失败');
  }
};

/**
 * 检查GitHub OAuth配置是否完整
 */
export const isGitHubConfigured = (): boolean => {
  return !!(GITHUB_CONFIG.clientId && GITHUB_CONFIG.clientSecret);
};